import {
	post
} from '@/common/axios.js'
import {
	register,
	sendMessage,
	loginApi
} from '@/common/path.js'
export default {
	namespaced: true,
	state: {
		userInfo: {}, //用户信息
		code: '', //验证码

	},
	getters: {

	},
	mutations: {
		SET_REGISTER(state, data) {
			state.userInfo = data
		},
		SET_CODE(state, data) {
			state.code = data
		},
	},
	actions: {
		//登录
		loginApi({
			commit,
			dispatch
		}, args = {}) {
			return new Promise((resolve, reject) => {
				post(loginApi, args).then(res => {
					if (res.code == 0) {
						resolve(res.data)
						commit('SET_REGISTER', res.data)
						uni.showToast({
							title: '登录成功',
							icon: 'none'
						})
						uni.setStorageSync('userInfo', res.data)
						setTimeout(r => {
							uni.reLaunch({
								url: '/pages/square/index'
							})
						}, 1000)
					} else {
						reject(res)
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(e => reject(e))
			})
		},

		//注册
		registerApi({
			commit,
			dispatch
		}, args = {}) {
			return new Promise((resolve, reject) => {
				post(register, args).then(res => {
					if (res.code == 0) {
						resolve(res.data)
						commit('SET_REGISTER', res.data)
						uni.setStorageSync('userInfo', res.data)
						uni.showToast({
							title: '注册成功',
							icon: 'none'
						})
						setTimeout(r => {
							uni.reLaunch({
								url: '/pages/square/index'
							})
						}, 1000)
					} else {
						reject(res)
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(e => reject(e))
			})
		},
		//获取验证码
		sendMessage({
			commit,
			dispatch
		}, args = {}) {
			return new Promise((resolve, reject) => {
				post(sendMessage, args).then(res => {
					if (res.code == 0) {
						resolve(res)
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
						const TIME_COUNT = 60;
						let timer = false
						let show = true
						let count;
						console.log('con', count);
						if (!timer) {
							count = TIME_COUNT;
							show = false;
							timer = setInterval(() => {
								commit('SET_CODE', count);
								if (count > 0 && count <= TIME_COUNT) {
									count -= 1;
								} else {
									show = true;
									clearInterval(timer);
									timer = null;
								}
							}, 1000);
						}
					} else {
						reject(res)
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})

					}
				}).catch(e => reject(e))
			})
		},
	},

}
